package com.wuze.cloud.adapter;

import com.wuze.cloud.dao.SysFileDao;
import com.wuze.cloud.dao.SysFolderDao;
import com.wuze.cloud.dao.SysRecyclingDao;
import com.wuze.cloud.pojo.SysFileDO;
import com.wuze.cloud.pojo.SysFolderDO;
import com.wuze.cloud.pojo.SysRecyclingDO;
import com.wuze.cloud.request.SysRecyclingQuery;
import com.wuze.cloud.response.SysRecyclingResponse;
import org.assertj.core.util.Lists;
import org.assertj.core.util.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

import static com.wuze.cloud.enums.SysStateEnum.RECYCLING;

/**
 * @Author wuze
 * @Date 2023/5/25 20:04
 * @ClassName: SysRecyclingAdapter
 * @Description: TODO
 */
@Component
public class SysRecyclingAdapter {

    @Autowired
    private SysRecyclingDao recyclingDao;

    @Autowired
    private SysFileDao fileDao;

    @Autowired
    private SysFolderDao folderDao;

    @Autowired
    private SysFileAdapter fileAdapter;

    @Autowired
    private SysFolderAdapter folderAdapter;

    public SysRecyclingResponse buildSysRecyclingResponse(SysRecyclingQuery query) {
        SysRecyclingResponse response = new SysRecyclingResponse();
        //分页查询回收站文件
        List<SysRecyclingDO> list = recyclingDao.findByPage(query);
        //提取文件ID和文件夹ID
        List<Long> fileIds = Lists.newArrayList();
        List<Long> folderIds = Lists.newArrayList();
        list.forEach(recycling->{
            if(Objects.nonNull(recycling.getFileId())){
                fileIds.add(recycling.getFileId());
            }
            if(Objects.nonNull(recycling.getFolderId())){
                folderIds.add(recycling.getFolderId());
            }
        });
        //构建响应实体
        List<SysFileDO> files = Lists.newArrayList();
        List<SysFolderDO> folders = Lists.newArrayList();

        if(!CollectionUtils.isEmpty(fileIds)){
            files.addAll(fileDao.findByIds(Sets.newHashSet(fileIds), RECYCLING.name()));
        }
        if(!CollectionUtils.isEmpty(folderIds)){
            folders.addAll(folderDao.findByIds(Sets.newHashSet(folderIds)));
        }
        response.setFiles(fileAdapter.buildSysFileVOS(files));
        response.setFolders(folderAdapter.buildSysFolderVOS(folders));
        response.setTotal(files.size()+folders.size());
        return response;
    }
}
